package org.funtester.performance.books.chapter08.section3;

import com.funtester.fungrpc.QueryRequest;
import com.funtester.fungrpc.QueryResponse;
import com.funtester.fungrpc.UserServiceGrpc;
import com.google.common.util.concurrent.ListenableFuture;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import org.funtester.performance.books.chapter03.section3.ThreadTask;
import org.funtester.performance.books.chapter03.section4.TaskExecutor;
import org.funtester.performance.books.chapter04.section3.RandomTool;

import java.util.ArrayList;
import java.util.List;

public class NonBlockingCase {

    public static void main(String[] args) throws InterruptedException {
        ManagedChannel managedChannel = ManagedChannelBuilder// 创建连接builder对象
                .forAddress("127.0.0.1", 8080)// 指定地址和端口
                .usePlaintext()// 使用明文传输,不使用ssl安全连接
                .build();// 创建连接

        UserServiceGrpc.UserServiceFutureStub userServiceFutureStub = UserServiceGrpc.newFutureStub(managedChannel);
        int totalNum = 1000;// 总执行次数
        int threadNum = 8;// 线程数
        int rumpUpTime = 20;// Rump-Up运行时间
        List<ThreadTask> tasks = new ArrayList<>();// 任务集合
        List<Integer> userIds = new ArrayList<>();// 用户ID集合
        for (int i = 100000; i < 2000000; i++) {// 生成100000-2000000的用户ID
            userIds.add(i);// 添加到用户ID集合
        }
        for (int i = 0; i < threadNum; i++) {
            ThreadTask threadTask = new ThreadTask() {

                @Override
                public void test() {
                    int userId = RandomTool.getRandomElement(userIds);// 随机获取用户ID
                    QueryRequest queryRequest = QueryRequest.newBuilder().setId(userId).build();
                    ListenableFuture<QueryResponse> queryResponseFuture = userServiceFutureStub.queryUser(queryRequest);// 执行用户信息查询
                    QueryResponse queryResponse = null;// 阻塞获取用户信息查询结果
                    try {
                        queryResponse = queryResponseFuture.get();
                    } catch (Exception e) {
                        // 异常处理,这里省略
                    }
                    if (userId != queryResponse.getId()) {// 校验用户ID
                        errorNum++;// 出错次数+1
                    }
                }

            };
            threadTask.totalNum = totalNum;// 设置执行次数
            threadTask.costTime = new ArrayList<>(totalNum);// 设置任务的执行时间集合,设置容量,避免频繁扩容
            tasks.add(threadTask);// 添加任务到任务集合
        }
        TaskExecutor taskExecutor = new TaskExecutor(tasks, "用户信息查询", rumpUpTime);
        taskExecutor.start();// 启动任务执行器
        managedChannel.shutdown();// 关闭连接
    }

}
